const arr = global.get("points");
if (!arr || arr.length === 0) return;

let startAddress = null;
let currentAddress = null;
let quantity = 0;
let values = [];
let currentTag = null;

for (var i = 0; i < arr.length; i++) {
    const tag = arr[i];
    if (tag[2] == '__NAME__') {
        if (typeof(global.get(tag[3])) == 'undefined') {
            global.set(tag[3], 0);
        }
        
        const address = parseInt(tag[1]);
        const value = parseInt(global.get(tag[3]));
        
        // 如果是第一个元素或地址不连续
        if (startAddress === null || address !== currentAddress + 1) {
            // 如果有待发送的数据，先发送
            if (startAddress !== null) {
                msg.payload = {
                    value: values,
                    fc: 6,
                    unitid: 1,
                    address: startAddress,
                    quantity: quantity
                };
                msg.tag = currentTag; // 使用最后一个tag作为代表
                node.send(msg);
            }
            
            // 开始新的序列
            startAddress = address;
            currentAddress = address;
            quantity = 1;
            values = [value];
            currentTag = tag;
        } else {
            // 地址连续，添加到当前序列
            currentAddress = address;
            quantity++;
            values.push(value);
            currentTag = tag; // 更新为当前tag
        }
    }
}

// 发送最后一个序列
if (startAddress !== null) {
    msg.payload = {
        value: values,
        fc: 6,
        unitid: 1,
        address: startAddress,
        quantity: quantity
    };
    msg.tag = currentTag;
    node.send(msg);
}